#!/usr/bin/bash

print_help () {
    echo "babeld-cli [interfaces|neighbors|routes|xroutes|version]"
}

dump=$(echo -e "dump\nquit" | netcat ::1 33123 -n)

if [ ! "$1" ]; then
    print_help

elif [ "$1" == "interfaces" ]; then
    echo -e "Interface\tState\tNext hop"
    echo "$dump" | grep "^add interface" | awk '{ split($0,a," "); print a[3], "\t", a[5], "\t", a[7] }'

elif [ "$1" == "neighbors" ]; then
    echo -e "Neighbor ID\tIP address\tInterface\tReach\tRxcost\tTxcost\tCost"
    echo "$dump" | grep "^add neighbour" | awk '{ split($0,a," "); print a[3], "\t", a[5], "\t", a[7], "\t", a[9], "\t", a[13], "\t", a[15], "\t", a[17] }' 

elif [ "$1" == "routes" ]; then
    echo -e "Route ID\tPrefix\t\t\tInstalled\tID\t\t\tMetric\tRefmetrix\tNext hop\tInterface"
    echo "$dump" | grep "^add route" | awk '{ split($0,a," "); print a[3], "\t", a[5], "\t", a[9], "\t", a[11], "\t", a[13], "\t", a[15], "\t", a[17], "\t", a[19] }'

elif [ "$1" == "xroutes" ]; then
    echo -e "Prefix\t\t\tMetric"
    echo "$dump" | grep "^add xroute" | awk '{ split($0,a," "); print a[5], "\t", a[9] }'

elif [ "$1" == "version" ]; then
    version=$(echo "$dump" | grep "^version" | awk '{ split($0,a," "); print a[2] }')
    host=$(echo "$dump" | grep "^host" | awk '{ split($0,a," "); print a[2] }')
    id=$(echo "$dump" | grep "^my-id" | awk '{ split($0,a," "); print a[2] }')

    echo "Version: $version"
    echo "Host: $host"
    echo "Router ID: $id"
else
    print_help
fi
